import java.net.*;
import java.io.*;

public class SocketEchoThread extends Thread {
	private Socket socket;
	private TexasReceiver texasReceiver;
	private NotificationCenter notifier;
	private boolean host;
	private String tableName;
	public SocketEchoThread(Socket socket,TexasReceiver tr, NotificationCenter n) {
		this.socket = socket;
		texasReceiver = tr;
		notifier = n;
		
	}
	public void makeHost(boolean host, String tableName){
		this.host = host;
		this.tableName = tableName;
	}
	public void run() {
		try {
			BufferedReader responses = 
					new BufferedReader
					(new InputStreamReader(socket.getInputStream()));
			PrintWriter writer = new PrintWriter(socket.getOutputStream());
			//writer.println("Connection open.");
			//writer.println("I will echo a single message, then close.");
			System.out.print("Hit");
			StringBuilder sb = new StringBuilder();
			while (!responses.ready()){}
			System.out.print("Hit after while");
			boolean trip = false;
			int counter = 0;
			while (responses.ready()) {
				counter++;
				System.out.println("Counter:"+counter+"Message:"+sb);
				if (trip){
					sb.append("\n");
				}
				trip = true;
				System.out.println("Got here");
				sb.append(responses.readLine());
				System.out.println("Got here");
			}
			
			System.out.println("SecondHit");
			System.out.println("From: " + socket.getInetAddress() + ": " + sb);
			texasReceiver.setMostRecent(sb.toString());
			String response = handleCall(sb.toString());
			if (response != null){
				writer.print(response);
			}
			writer.flush();
			socket.close();
			System.out.print("Close");
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} 
	}
	private String handleCall(String message){
		String type = null;
		if (message.indexOf(":") != -1){
			type = message.substring(0,message.indexOf(":"));
		}
		else{
			type = message;
		}
		
		if (type.equals("deal_cards")){
			notifier.cardsReceived(new HandCards(message.substring(message.indexOf(":") + 2, message.length() - 1)));
		}
		else if (type.equals("turn")){
			notifier.playerMadeMove(new Turn(message.substring(message.indexOf(":") + 2, message.length() - 1)));
		}
		else if (type.equals("host_request")){
			if (host){
				return "True:"+tableName;
			}
			else{
				return "False";
			}
		}
		return null;
	}
}